package com.atguigu.srb.oss.controller;

import com.atguigu.srb.common.exception.SrbException;
import com.atguigu.srb.common.result.ResponseEnum;
import com.atguigu.srb.common.result.Result;
import com.atguigu.srb.oss.service.FileService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.InputStream;

/**
 * ClassName: FileController
 * Package: com.atguigu.srb.oss.controller
 * Description:
 *
 * @Author 王晓龙
 * @Create 2023/3/31 3:22
 * @Version 1.0
 */
@Api(tags = "阿里云文件管理")
@RestController
@RequestMapping("/api/oss")
public class OSSController {
    @Resource
    private FileService fileService;

    //文件上传
    @ApiOperation("文件上传")
    @PostMapping("/upload")
    public Result upload(
            @ApiParam(value = "文件", required = true)
            @RequestParam("file") MultipartFile file,

            @ApiParam(value = "存放文件的根文件夹", required = true)
            @RequestParam("module") String module
    ){
        try {
            InputStream inputStream = file.getInputStream();
            String originalFilename = file.getOriginalFilename();
            String uploadUrl = fileService.upload(inputStream, module, originalFilename);
            //返回R对象
            return Result.ok().message("文件上传成功").data("url", uploadUrl);
        } catch (Exception e) {
            throw new SrbException(ResponseEnum.UPLOAD_ERROR);
        }
    }

    @ApiOperation("文件删除")
    @DeleteMapping("/remove")
    public Result remove(
            @ApiParam("要删除文件的访问url")
            @RequestParam("fileUrl") String fileUrl){
        fileService.remove(fileUrl);
        return Result.ok().message("删除成功");
    }
}